package com.zg.third.qcc.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.zg.third.api.domain.vo.ZtQccEnterpriseInfoVo;
import com.zg.third.api.domain.vo.ZtQccResponse;
import com.zg.third.qcc.enm.ZtQccUrlEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 企查查工具类
 */
@Slf4j
@Component
public class ZtQccUtil {

    @Value("${qcc.appId}")
    private String appId = "testAppId";

    @Value("${qcc.interfaceId}")
    private String interfaceId = "61b27036d5674f56b7d8c28c33891fd5";

    @Value("${qcc.sm4Key}")
    private String sm4Key = "CEA6BFD1609181BC380B453A723F0D19";

    @Value("${qcc.customerPrivateKey}")
    private String customerPrivateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgjj4Rk+b0YjwO+UwXofnHf4bK+kaaY5Btkd8nMP2VimmgCgYIKoEcz1UBgi2hRANCAAQqlALW4qGC3bP1x3wo5QsKxaCMEZJ2ODTTwOQ+d8UGU7GoK/y/WMBQWf5upMnFU06p5FxGooXYYoBtldgm03hq";

    @Value("${qcc.sysPublicKey}")
    private String sysPublicKey = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE66H9p8wnQagnQcwkrlZ3xfoFJzjTSqJFIzgCMR0ShBxWeId9/UpQWpa2p4vUGxwBK+ZvBGJxScN1dOkJtjk53Q==";

    @Value("${qcc.url}")
    private String url = "http://172.16.150.213:9908";

    private String request(ZtQccUrlEnum qccUrlEnum, Map<String, Object> requestParam) {
        //排序后的请求入参
        TreeMap<String, Object> sortMap = SysEncryptionUtil.sortField(requestParam);
        //生成签名
        String sign;
        try {
            sign = SysEncryptionUtil.sign(customerPrivateKey, appId, JSONUtil.toJsonStr(sortMap));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用企查查接口失败: 生成签名异常", e);
            return null;
        }
        //入参中加入签名
        sortMap.put("sign", sign);
        //加密数据
        String cipherText;
        try {
            cipherText = SysEncryptionUtil.encryptEcb(sm4Key, JSONUtil.toJsonStr(sortMap));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用企查查接口失败: 加密数据异常", e);
            return null;
        }
        //调用统一接口
        String requestUrl = url + qccUrlEnum.getUrl();
        log.info("调用企查查接口，请求地址: {}", requestUrl);
        HttpRequest request = HttpUtil.createPost(requestUrl);
        Map<String, String> headers = new HashMap<>();
        headers.put("appId", appId);
        headers.put("interfaceId", interfaceId);
        request.addHeaders(headers);
        request.body(cipherText);
        //获取返回结果
        log.info("调用企查查接口，请求数据: {}", cipherText);
        HttpResponse response = request.executeAsync();
        String responseStr = response.body();
        log.info("调用企查查接口，响应数据: {}", responseStr);
        JSONObject resultJson = JSONUtil.parseObj(responseStr);
        String data = resultJson.getStr("data");

        String decryptStr;
        try {
            decryptStr = SysEncryptionUtil.decryptEcb(sm4Key, data);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用企查查接口失败: 解密响应数据异常", e);
            return null;
        }
        if (JSONUtil.isJson(decryptStr)) {
            JSONObject decryptJson = JSONUtil.parseObj(decryptStr);
            String returnSign = decryptJson.getStr("sign");
            decryptJson.remove("sign");
            TreeMap<String, Object> returnSortMap = SysEncryptionUtil.sortField(decryptJson);
            //验签
            boolean verifySign;
            try {
                verifySign = SysEncryptionUtil.verifySign(
                        sysPublicKey, appId, returnSign, JSONUtil.toJsonStr(returnSortMap));
            } catch (Exception e) {
                e.printStackTrace();
                log.error("调用企查查接口失败: 验签异常", e);
                return null;
            }
            if (verifySign) {
                //验签成功
                log.info("调用企查查接口, 验签成功, {}", decryptStr);
                //处理业务逻辑
                ZtQccResponse ztQccResponse = JSONUtil.toBean(decryptJson, ZtQccResponse.class);
                if ("200".equals(ztQccResponse.getStatus())) {
                    return JSONUtil.toJsonStr(ztQccResponse.getResult());
                } else {
                    log.error("调用企查查接口失败: {}", ztQccResponse.getMessage());
                }
            } else {
                //验签失败
                log.error("调用企查查接口失败: 验签失败, {}", decryptStr);
            }
        } else {
            log.error("调用企查查接口失败: 响应数据不符合要求, {}", decryptStr);
        }

        return null;
    }

    public ZtQccEnterpriseInfoVo loadData(String keyword) {
        //原始接口请求入参
        JSONObject requestParams = new JSONObject();
        requestParams.set("keyword", keyword);
        requestParams.set("lastDay", 30);
        String responseStr = request(ZtQccUrlEnum.ENTERPRISE, requestParams);
        if (StrUtil.isBlank(responseStr)) {
            return null;
        }
        return JSONUtil.toBean(responseStr, ZtQccEnterpriseInfoVo.class);
    }
}
